const { getCarouselByPosition,getHotPackages  } = require("../../api/index.js")

Page({
    data: {
        value: "",
        swiperOptions: {
            indicatorDots: true,
            autoplay: true,
            interval: 3000,
            duration: 1000,
            swiperData: [] // 轮播图数据存放在这里
        },
        navData: [
            { text: "运动器械", icon: "like", color: "#ff0000" },
            { text: "蛋白粉", icon: "star", color: "#ff0000" },
            { text: "健生器械", icon: "fire", color: "#ff0000" },
            { text: "运动服饰", icon: "gift", color: "#ff0000" },
            { text: "健康食品", icon: "phone", color: "#ff0000" },
            { text: "运动补剂", icon: "gem", color: "#ff0000" },
            { text: "智能穿戴", icon: "gift-card", color: "#ff0000" },
            { text: "瑜伽用品", icon: "smile", color: "#ff0000" }
        ],
        packages: [] // 新增：存储套餐数据
    },

    onLoad() {
        // 加载轮播图数据
        this.loadCarousel();
        this.loadHotPackages(); // 新增：加载热门套餐
    },

    // 加载轮播图
    loadCarousel() {
      getCarouselByPosition(4).then(res => {
        console.log("轮播图接口返回：", res);
        // 适配接口返回格式（res.data 是轮播图数组，无需再取 res.data.data）
        if (res.code === 0 && res.data && res.data.length > 0) {
          const swiperData = res.data.map(item => ({ url: item.imageUrl }));
          console.log("转换后的数据：", swiperData); // 确认格式为 [{url: "图片地址"}]
          this.setData({
            "swiperOptions.swiperData": swiperData
          }, () => {
            // setData 回调中验证数据是否更新
            console.log("更新后的数据：", this.data.swiperOptions.swiperData);
            // 同时打印组件接收的属性（若 swiper 组件支持，可在组件内打印 properties）
          });
        } else {
          wx.showToast({ title: "轮播图数据格式异常", icon: "none" });
        }
      }).catch(err => {
        console.log("轮播图请求异常：", err);
        wx.showToast({ title: "网络错误", icon: "none" });
      });
    },
    
    loadHotPackages() {
      getHotPackages().then(res => {
          console.log("热门套餐接口返回：", res); // 检查是否有数据返回
          if (res.code === 0 && res.data && res.data.length > 0) {
              // 处理价格格式
              const packages = res.data.map(item => ({
                  ...item,
                  priceStr: item.price.toFixed(2)
              }));
              this.setData({ packages }); // 将数据存入data
          } else {
              wx.showToast({ title: "套餐数据加载失败", icon: "none" });
          }
      }).catch(err => {
          console.error("套餐请求失败：", err);
          wx.showToast({ title: "网络错误", icon: "none" });
      });
  },
    // 点击搜索框
    clickSearch() {
        wx.navigateTo({
            url: '/pages/search/search'
        });
    },
     // 跳转到套餐详情页
  goToPackageDetail(e) {
    const packageId = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/package-detail/package-detail?id=${packageId}`
    });
  }
})